<script setup>
import { ref, computed, onMounted, watch, defineExpose } from 'vue'
import { Delete, Plus, Minus, ShoppingBag } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import store from '@/store'

// 尺码选择相关的状态
const sizeDialogVisible = ref(false)
const selectedSize = ref(null)
const selectedProduct = ref(null)

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'checkout'])

// 购物车商品列表
const cartItems = ref(JSON.parse(store.getStore('cartItems') || '[]'))

// 添加商品到购物车的方法，供外部调用
const addProduct = (product) => {
  selectedProduct.value = product
  selectedSize.value = null
  sizeDialogVisible.value = true
}

// 确认添加商品到购物车
const confirmAddToCart = () => {
  if (!selectedSize.value) {
    ElMessage.warning('请选择尺码')
    return
  }

  const product = selectedProduct.value
  // 检查商品是否已在购物车中（同一商品同一尺码）
  const existingItem = cartItems.value.find(item => 
    item.id === product.id && item.size === selectedSize.value
  )
  
  if (existingItem) {
    // 如果已存在相同尺码，增加数量
    existingItem.quantity++
    ElMessage.success(`已将 ${product.name} (${selectedSize.value}码) 的数量增加到 ${existingItem.quantity}`)
  } else {
    // 如果不存在，添加到购物车
    cartItems.value.push({
      id: product.id,
      name: product.name,
      brand: product.brand,
      price: product.price,
      image: product.image || 'https://via.placeholder.com/100x100',
      size: selectedSize.value,
      quantity: 1
    })
    ElMessage.success(`已将 ${product.name} (${selectedSize.value}码) 添加到购物车`)
  }
  
  // 保存到本地存储
  store.setStore('cartItems', JSON.stringify(cartItems.value))
  // 关闭对话框
  sizeDialogVisible.value = false
}

// 增加商品数量
const increaseQuantity = (item) => {
  item.quantity++
  store.setStore('cartItems', JSON.stringify(cartItems.value))
}

// 减少商品数量
const decreaseQuantity = (item) => {
  if (item.quantity > 1) {
    item.quantity--
    store.setStore('cartItems', JSON.stringify(cartItems.value))
  }
}

// 删除商品
const removeItem = (item) => {
  const index = cartItems.value.findIndex(i => i.id === item.id)
  if (index > -1) {
    cartItems.value.splice(index, 1)
    store.setStore('cartItems', JSON.stringify(cartItems.value))
    ElMessage.success('商品已从购物车中移除')
  }
}

// 清空购物车
const clearCart = () => {
  cartItems.value = []
  store.setStore('cartItems', '[]')
}

// 计算购物车总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.price * item.quantity
  }, 0)
})

// 计算购物车商品总数
const totalItems = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.quantity
  }, 0)
})

// 关闭购物车抽屉
const closeDrawer = () => {
  emit('update:visible', false)
}

// 处理结算
const handleCheckout = () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车是空的')
    return
  }
  emit('checkout')
  clearCart()
}

// 暴露方法给父组件
defineExpose({
  addProduct
})
</script>

<template>
  <el-drawer
    v-model="props.visible"
    title="购物车"
    size="30%"
    @update:visible="(val) => emit('update:visible', val)"
  >
    <!-- 尺码选择对话框 -->
    <el-dialog
      v-model="sizeDialogVisible"
      title="选择尺码"
      width="30%"
      :modal="true"
      :append-to-body="true"
    >
      <div class="size-selection">
        <el-radio-group v-model="selectedSize">
          <el-radio 
            v-for="size in selectedProduct?.sizes" 
            :key="size" 
            :label="size"
          >
            {{ size }}
          </el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="sizeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddToCart">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <div class="cart-container">
      <!-- 空购物车提示 -->
      <div v-if="cartItems.length === 0" class="empty-cart">
        <el-icon :size="48"><ShoppingBag /></el-icon>
        <p>购物车是空的</p>
      </div>
      
      <!-- 购物车商品列表 -->
      <div v-else class="cart-items">
        <el-card v-for="item in cartItems" :key="item.id" class="cart-item">
          <div class="item-content">
            <img :src="item.image" :alt="item.name" class="item-image">
            <div class="item-info">
              <h4>{{ item.name }}</h4>
              <p class="brand">{{ item.brand }}</p>
              <p class="size">尺码：{{ item.size }}</p>
              <p class="price">¥{{ item.price }}</p>
            </div>
            <div class="item-actions">
              <div class="quantity-control">
                <el-button
                  :icon="Minus"
                  circle
                  @click="decreaseQuantity(item)"
                  :disabled="item.quantity <= 1"
                />
                <span class="quantity">{{ item.quantity }}</span>
                <el-button
                  :icon="Plus"
                  circle
                  @click="increaseQuantity(item)"
                />
              </div>
              <el-button
                type="danger"
                :icon="Delete"
                circle
                @click="removeItem(item)"
              />
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 购物车底部 -->
      <div class="cart-footer">
        <div class="total-price">
          总计: <span>¥{{ totalPrice }}</span>
        </div>
        <el-button
          type="primary"
          :disabled="cartItems.length === 0"
          @click="handleCheckout"
        >
          结算
        </el-button>
      </div>
    </div>
  </el-drawer>
</template>

<style scoped>
.cart-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.empty-cart p {
  margin-top: 16px;
  font-size: 16px;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px;
}

.cart-item {
  margin-bottom: 16px;
}

.item-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-info h4 {
  margin: 0 0 8px;
  font-size: 16px;
}

.brand {
  color: #909399;
  margin: 0 0 4px;
}

.size {
  color: #666;
  margin: 0 0 4px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  margin: 0;
}

.item-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: flex-end;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity {
  min-width: 24px;
  text-align: center;
}

.cart-footer {
  margin-top: auto;
  padding: 16px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-price {
  font-size: 18px;
}

.total-price span {
  color: #f56c6c;
  font-weight: bold;
}
</style>